/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.hanze.shoestring.dao.impl;

import java.util.List;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import nl.hanze.shoestring.dao.KlantDAO;
import nl.hanze.shoestring.domain.*;

/**
 *
 * @author alex
 */
public class KlantDAOImpl extends BaseDAOImpl<Klant> implements KlantDAO{

    public KlantDAOImpl() {
    }
    
    public List<Klant> find(String name){
        boolean hasName = name != null && name.length() > 0;
        
        if (!hasName) {
            return getAll();
        }

        open();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Klant> query = cb.createQuery(Klant.class);
        Root<Klant> klant = query.from(Klant.class);
        Join<Klant, Persoon> persoon = klant.join(Klant_.persoon);
        

        Predicate p = cb.or(cb.like(persoon.get(Persoon_.achternaam), name + "%"),cb.like(persoon.get(Persoon_.achternaam), name + "%"), 
                cb.like(persoon.get(Persoon_.email), "%" + name + "%"));               

        query.where(p);

        TypedQuery<Klant> typedQuery = em.createQuery(query);
        return typedQuery.getResultList();
    }
    
    

}
